项目结构

image-20210920183647448

大概就这样一个简单的架构,以nacos为服务注册中心,然后访问服务时,网关转发这些请求到对应的服务。

导入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>WeVote</artifactId>
<groupId>com.fizzy</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>wevote-gateway</artifactId>

<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

<!-- 负载均衡loadbalancer -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
</dependencies>

</project>

由于springcloud2020弃用了Ribbon,因此Alibaba在2021版本nacos中删除了Ribbon的jar包,因此无法通过lb路由到指定微服务,出现了503情况。

所以只需要引入springcloud loadbalancer包即可

配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server:
port: 80

spring:
application:
name: gateway
cloud:
nacos:
discovery:
server-addr: localhost:8848 # 注册到Nacos中
gateway:
routes:
- id: gateway-user-service # 路由唯一表示
uri: lb://user-service # 需要转发的服务,lb表示负载均衡
predicates:
- Path=/user-service/** # 转发以user-service开头的请求
filters:
- StripPrefix=1 # 删除路径中的user-service

这样我们访问localhost:80/user-service/user-api,gateway就会帮我们转发到user-service服务,也就是localhost:8001/user-api

测试

比如user-service中提供了一个生成验证码的接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RestController
public class VerifyController {
@Autowired
RedisUtil redisUtil;

@GetMapping("/vercode")
public void code(HttpServletRequest req, HttpServletResponse resp) throws IOException {
VerifyCode vc = new VerifyCode();
BufferedImage image = vc.getImage();
String text = vc.getText();
redisUtil.set("VerifyCode", text);
HttpSession session = req.getSession();
session.setAttribute("index_code", text);
VerifyCode.output(image, resp.getOutputStream());
}
}

然后我们服务器访问localhost/user-service/vercode

就能生成验证码

image-20210920184836572

跨域设置

参考官方文档,在application.yml中配置

1
2
3
4
5
6
7
8
9
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "https://docs.spring.io"
allowedMethods:
- GET

参考

springcloud2020版本gateway+nacos,服务报错503 Service Unavailable_疯狂的炫的博客-CSDN博客